<template>
  <div class="login-page">
    <van-nav-bar
  title="账户登录"
   left-arrow
    @click-left="onClickLeft"
/>
<van-form @submit="onSubmit">
  <van-field
    v-model="username"
    name="username"
    placeholder="请输入用户名"
    :rules="[{ required: true, message: '请填写用户名' },
    {pattern:/^\w{5,}$/, message: '用户名至少包含五个字符'}
    ]"
  />
  <van-field
    v-model="password"
    type="password"
    name="password"
    placeholder="请输入密码"
    :rules="[{ required: true, message: '请填写密码' },
    {pattern:/^\w{6,}$/, message: '用户名至少包含六个字符'}
    ]"
  />
  <div style="margin: 16px;">
    <van-button  block type="info" native-type="submit">登录</van-button>
  </div>
</van-form>
<router-link class="link" to="/register">注册账号</router-link>
  </div>
</template>

<script>
// 引入api内设置的登录接口和utils内的获取token
import { login } from '@/api/user'
import { setToken } from '@/utils/storage'

export default {
  name: 'login-page',
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    // 表单点击提交后如果成功了获取token和显示登录成功
    async onSubmit (val) {
      // console.log('触发了', val)
      const { body } = await login(val)
      console.log(body)
      // 将token存起来
      setToken(body.token)
      this.$toast.success('登录成功')
      // 跳转到首页
      this.$router.push('/mylogin')
    },
    onClickLeft () {
      this.$router.push('/register')
    }
  }

}
</script>

<style lang="less" scoped>
.link {
  color: #069;
  font-size: 12px;
  padding-right: 165px;
  float: right
}
</style>
